/**
 * 程序主入口文件
 */
const { program } = require("commander")
const path = require("path")
const chalk = require("chalk")
const Migrator = require("./migrator")
const { version } = require("../package.json")

// 配置命令行参数
program
  .name("module-migrate")
  .version(version)
  .description(
    "A tool for analyzing project dependencies and migrating them to a new project"
  )
  .option("-s, --source <path>", "Source project path", "./src")
  .option("-e, --entry <path>", "Entry file/directory path", "./src/index.js")
  .option("-t, --target <path>", "Target path", "./dist")
  .option("-c, --config <path>", "Configuration file path")
  .option("--no-report", "Do not generate dependency report")
  .option("-v, --verbose", "Show detailed logs")
  .on("--help", () => {
    console.log("")
    console.log("Examples:")
    console.log(
      "  $ module-migrate --source ./my-project/src --entry ./my-project/src/components/Feature --target ./new-project"
    )
    console.log(
      "  $ module-migrate -s ./src -e ./src/modules/auth -t ./extracted-auth"
    )
    console.log("  $ module-migrate --config ./migrate.config.js")
  })
  .parse(process.argv)

// 获取命令行选项
const options = program.opts()

// 显示欢迎信息
console.log(chalk.blue("=============================================="))
console.log(chalk.blue(`      Module Migration Tool v${version}`))
console.log(chalk.blue("=============================================="))

/**
 * 加载用户配置文件（如果有）
 * @param {string} configPath - 配置文件路径
 * @returns {Object} 用户配置
 */
function loadUserConfig(configPath) {
  if (!configPath) {
    return {}
  }

  try {
    const fullPath = path.resolve(configPath)
    console.log(`Loading config file: ${chalk.yellow(fullPath)}`)
    return require(fullPath)
  } catch (error) {
    console.error(chalk.red(`Failed to load config file: ${error.message}`))
    return {}
  }
}

// 主函数
async function main() {
  try {
    // 解析配置
    const userConfig = options.config ? loadUserConfig(options.config) : {}

    // 创建迁移器实例
    const migrator = new Migrator({
      sourcePath: options.source,
      entryPoint: options.entry,
      targetPath: options.target,
      verbose: options.verbose,
      report: {
        generateReport: options.report,
      },
      ...userConfig,
    })

    // 执行迁移
    await migrator.migrate()
  } catch (error) {
    console.error(chalk.red("Error during migration:"), error.message)
    process.exit(1)
  }
}

// 运行主函数
main().catch((error) => {
  console.error(chalk.red("Runtime error:"), error.message)
  process.exit(1)
})
